#include "geompointer.h"

using namespace G3;

G3::GEOM_POINTER::GEOM_POINTER () {
    vertices = NULL;
    texcoords = NULL;
    normals = NULL;
    tangents = NULL;
    indexes = NULL;
    materials = NULL;

    num_vertices = 0;
    num_indexes = 0;
    num_materials = 0;

    material_applied = false;
    current_material = 0;

    log = &G3::MainLog;
}

G3::GEOM_POINTER::~GEOM_POINTER () {
    clear ();
}

//==============================================================================
// Initializes the DisplayList
//==============================================================================
void G3::GEOM_POINTER::init (uint nv, G3::VEC3F *v, uint nid, uint *id, uint nm, G3::MATERIAL *m, G3::VEC2F *uv, G3::VEC3F *n, G3::VEC3F *t) {
    num_vertices = nv;
    num_indexes = nid;
    num_materials = nm;

    vertices = v;
    texcoords = uv;
    normals = n;
    tangents = t;
    indexes = id;
    materials = m;

    // Are the pointers valid?
    if (vertices == NULL || indexes == NULL) {
        if (log != NULL)
            log->Report ("GEOM_POINTER::init: At least vertices and indexes are needed to define a buffer\n");
        return;
    }
}

//==============================================================================
// Binds a material
//==============================================================================
bool G3::GEOM_POINTER::bind_material (int mat_id) {
    if (mat_id < 0) {
        material_applied = false;
        return true;
    }

    if (materials == NULL) {
        if (log)
            log->Report ("GEOM_POINTER::bind_material: There are no materials in this GEOM_POINTER\n");
        return false;
    }
    if (mat_id >= (int) num_materials) {
        if (log)
            log->Report ("GEOM_POINTER::bind_material: There are only %d materials in this GEOM_POINTER. However, material nr. %d was asked\n", num_materials, mat_id);
        return false;
    }

    material_applied = true;
    current_material = mat_id;

    materials [mat_id].glApply ();

    return true;
}

//==============================================================================
// Unbinds the last bound material
//==============================================================================
bool G3::GEOM_POINTER::unbind_material () {
    if (!material_applied)
        return false;

    Assert (materials, "Impossible but true: There are no materials, but one of them has been bound");
    Assert (current_material < num_materials, "Impossible but true: A nonexistent material has been bound");

    materials [current_material].glUnApply ();

    material_applied = false;
    current_material = 0;

    return true;
}

void G3::GEOM_POINTER::clear () {
    //! \todo Maybe we should store the DisplayList ID's and destroy them here instead of the batch destructor
}
